package com.lingz.manager.modules.sms.service.Impl;

import cn.hutool.core.util.RandomUtil;
import com.lingz.manager.modules.base.service.UserService;
import com.lingz.manager.modules.sms.service.SMSService;
import com.lingz.manager.modules.sms.utils.AliyunSmsUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.lingz.manager.modules.base.entity.User;

import java.util.Objects;
import java.util.concurrent.TimeUnit;


/**
 * @author mengquanqi
 * @version V1.0
 * @Package com.lingz.manager.modules.sms.service.Impl
 * @Description
 * @date 2023/10/12 18:43
 */

@Slf4j
@Service
public class SMSServiceImpl implements SMSService {

    @Autowired
    UserService userService;

    @Value("${aliyun.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.signName}")
    private String signName;

    @Value("${aliyun.domain}")
    private String domain;

    @Value("${aliyun.templateCode}")
    private String templateCode;

    @Value("${xboot.token.redis}")
    private Boolean tokenRedis;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public void sendSms(String phone) {
        checkPhone(phone);
        String smsCode = RandomUtil.randomNumbers(6);
        try {
//            AliyunSmsUtils.sendCaptcha(accessKeyId, accessKeySecret, phone, signName, templateCode, domain, smsCode);
            if (tokenRedis){
                System.out.println("开启Redis");
                stringRedisTemplate.opsForValue().set(phone+smsCode,smsCode,60*3, TimeUnit.SECONDS);
            }else {
                System.out.println("未开启Redis");
                stringRedisTemplate.opsForValue().set(phone+smsCode,smsCode,60*3, TimeUnit.SECONDS);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void checkPhone(String phone) {
        // 是否注册
        User user = userService.findByMobile(phone);
        if (Objects.nonNull(user)){
            throw new RuntimeException("电话号码已存在，请直接登录！");
        }
    }
}
